// 邮件交互功能模块（滑动删除、右键菜单、长按等）
const EmailInteractionsManager = {
    // 初始化滑动删除功能
    initSwipeDelete: function() {
        const wrapper = document.getElementById('email-list-wrapper');
        if (!wrapper) return;

        let startX = 0;
        let startY = 0;
        let currentX = 0;
        let isDragging = false;
        let isHorizontalSwipe = false;
        let swipedItem = null;
        let swipedInner = null;
        let itemWidth = 0;
        let hasVibrated = false;
        let currentTipIndex = null;
        let currentTipState = null;

        // 关闭已滑开的邮件项
        const closeSwipedItem = (animated = true) => {
            if (swipedItem && swipedInner) {
                swipedInner.style.transition = animated ? 'transform 0.3s ease' : 'none';
                swipedInner.style.transform = 'translateX(0px)';
                swipedItem.removeClass('swiping');
                swipedItem = null;
                swipedInner = null;
            }
            if (currentTipIndex !== null) {
                layer.close(currentTipIndex);
                currentTipIndex = null;
            }
            hasVibrated = false;
            currentTipState = null;
        };

        wrapper.addEventListener('touchstart', function(e) {
            const innerElement = e.target.closest('.email-item-inner');
            if (!innerElement) return;

            if (swipedItem && !swipedItem[0].contains(innerElement)) {
                closeSwipedItem();
            }

            isDragging = true;
            isHorizontalSwipe = false;
            swipedInner = innerElement;
            swipedItem = $(innerElement).closest('.email-item');
            startX = e.touches[0].clientX;
            startY = e.touches[0].clientY;
            hasVibrated = false;
            currentTipState = null;
            
            itemWidth = swipedItem[0].offsetWidth;

            const currentTransform = window.getComputedStyle(swipedInner).transform;
            currentX = currentTransform === 'none' ? 0 : parseFloat(currentTransform.split(',')[4]);

            swipedInner.style.transition = 'none';
        });

        wrapper.addEventListener('touchmove', function(e) {
            if (!isDragging || !swipedInner) return;

            const moveX = e.touches[0].clientX;
            const moveY = e.touches[0].clientY;
            const deltaX = moveX - startX;
            const deltaY = moveY - startY;

            if (!isHorizontalSwipe && (Math.abs(deltaX) > 5 || Math.abs(deltaY) > 5)) {
                isHorizontalSwipe = Math.abs(deltaX) > Math.abs(deltaY);
            }

            if (!isHorizontalSwipe) return;

            let newX = currentX + deltaX;

            if (newX > 0) newX = 0;

            if (newX < 0) {
                if (e.cancelable) {
                    e.preventDefault();
                }
                newX = Math.max(newX, -itemWidth * 0.8);
                swipedInner.style.transform = `translateX(${newX}px)`;
                
                const swipeRatio = Math.abs(newX) / itemWidth;
                
                if (swipeRatio >= 0.3 && !hasVibrated) {
                    if (navigator.vibrate) {
                        navigator.vibrate(50);
                    }
                    hasVibrated = true;
                }
                
                if (swipeRatio >= 0.3) {
                    if (currentTipState !== 'delete') {
                        if (currentTipIndex !== null) {
                            layer.close(currentTipIndex);
                        }
                        currentTipIndex = layer.tips('松手后删除', swipedItem[0], {
                            tips: [1, '#ff5722'],
                            time: 0,
                            area: 'auto'
                        });
                        currentTipState = 'delete';
                    }
                } else if (swipeRatio > 0.05) {
                    if (currentTipState !== 'cancel') {
                        if (currentTipIndex !== null) {
                            layer.close(currentTipIndex);
                        }
                        currentTipIndex = layer.tips('松手取消', swipedItem[0], {
                            tips: [1, '#999'],
                            time: 0,
                            area: 'auto'
                        });
                        currentTipState = 'cancel';
                    }
                }
            }
        }, { passive: false });

        const handleTouchEnd = () => {
            if (!isDragging || !swipedInner) return;

            isDragging = false;
            swipedInner.style.transition = 'transform 0.3s ease';

            const finalTransform = window.getComputedStyle(swipedInner).transform;
            const finalX = finalTransform === 'none' ? 0 : parseFloat(finalTransform.split(',')[4]);
            
            if (currentTipIndex !== null) {
                layer.close(currentTipIndex);
                currentTipIndex = null;
            }
            
            const swipeRatio = Math.abs(finalX) / itemWidth;
            
            if (swipeRatio > 0.3) {
                const emailId = swipedItem.data('email-id');
                const accountId = EmailModule.cache.currentAccount;
                
                if (emailId && accountId) {
                    swipedItem.css({
                        transition: 'all 0.3s ease',
                        opacity: 0,
                        height: 0,
                        margin: 0,
                        padding: 0
                    });
                    
                    setTimeout(() => {
                        EmailOperationsManager.deleteEmail(accountId, emailId);
                        swipedItem = null;
                        swipedInner = null;
                    }, 300);
                }
            } else {
                swipedInner.style.transform = 'translateX(0px)';
                if(swipedItem) swipedItem.removeClass('swiping');
                swipedItem = null;
                swipedInner = null;
            }
            
            isHorizontalSwipe = false;
            hasVibrated = false;
            currentTipState = null;
        };
        
        wrapper.addEventListener('touchend', handleTouchEnd);
        wrapper.addEventListener('touchcancel', handleTouchEnd);

        // 删除按钮的点击事件
        $('#email-list-wrapper').off('click', '.delete-layer').on('click', '.delete-layer', function(e) {
            e.stopPropagation();
            const itemToDelete = $(this).closest('.email-item');
            if (itemToDelete.length > 0) {
                const emailId = itemToDelete.data('email-id');
                const accountId = EmailModule.cache.currentAccount;
                
                if (emailId && accountId) {
                    closeSwipedItem(false);
                    
                    itemToDelete.css({
                        transition: 'all 0.3s ease',
                        opacity: 0,
                        height: 0,
                        margin: 0,
                        padding: 0
                    });
                    
                    setTimeout(() => {
                        EmailOperationsManager.deleteEmail(accountId, emailId);
                    }, 300);
                }
            }
        });

        // 点击文档任何其他地方，关闭已滑开的项
        $(document).off('click.swipeDelete').on('click.swipeDelete', function(e) {
            if (swipedItem && !swipedItem[0].contains(e.target)) {
                closeSwipedItem();
            }
        });
    },

    // 初始化右键菜单和长按菜单
    initContextMenu: function() {
        // 创建上下文菜单DOM
        if ($('#email-context-menu').length === 0) {
            $('body').append('<div id="email-context-menu" class="email-context-menu"></div>');
        }
        
        const contextMenu = $('#email-context-menu');
        let longPressTimer = null;
        let longPressTarget = null;
        
        // 隐藏菜单函数
        const hideMenu = () => {
            contextMenu.removeClass('show');
        };
        
        // 显示菜单函数
        const showMenu = (x, y, emailItem) => {
            const emailId = emailItem.data('email-id');
            const accountId = EmailModule.cache.currentAccount;
            const isRead = !emailItem.hasClass('unread');
            const isSpecialFolder = ['Drafts', 'Sent'].includes(EmailModule.cache.currentFolder);
            
            let menuHtml = '';
            
            // 标记已读/未读
            if (!isSpecialFolder) {
                if (isRead) {
                    menuHtml += `
                        <div class="email-context-menu-item" data-action="mark-unread" data-email-id="${emailId}" data-account-id="${accountId}">
                            <i class="layui-icon layui-icon-email"></i>
                            <span>标记为未读</span>
                        </div>
                    `;
                } else {
                    menuHtml += `
                        <div class="email-context-menu-item" data-action="mark-read" data-email-id="${emailId}" data-account-id="${accountId}">
                            <i class="layui-icon layui-icon-ok-circle"></i>
                            <span>标记为已读</span>
                        </div>
                    `;
                }
            }
            
            // 移动邮件
            if (!isSpecialFolder) {
                menuHtml += `
                    <div class="email-context-menu-item" data-action="move" data-email-id="${emailId}" data-account-id="${accountId}">
                        <i class="layui-icon layui-icon-export"></i>
                        <span>移动邮件</span>
                    </div>
                `;
            }
            
            menuHtml += '<div class="email-context-menu-divider"></div>';
            
            // 删除
            if (!isSpecialFolder) {
                menuHtml += `
                    <div class="email-context-menu-item danger" data-action="delete" data-email-id="${emailId}" data-account-id="${accountId}">
                        <i class="layui-icon layui-icon-delete"></i>
                        <span>删除</span>
                    </div>
                `;
            }
            
            // 彻底删除
            menuHtml += `
                <div class="email-context-menu-item danger" data-action="permanent-delete" data-email-id="${emailId}" data-account-id="${accountId}">
                    <i class="layui-icon layui-icon-close-fill"></i>
                    <span>彻底删除</span>
                </div>
            `;
            
            contextMenu.html(menuHtml);
            
            contextMenu.css({ left: x + 'px', top: y + 'px' });
            contextMenu.addClass('show');
            
            const menuWidth = contextMenu.outerWidth();
            const menuHeight = contextMenu.outerHeight();
            const windowWidth = $(window).width();
            const windowHeight = $(window).height();
            
            let finalX = x;
            if (x + menuWidth > windowWidth) {
                finalX = windowWidth - menuWidth - 10;
            }
            
            let finalY = y;
            if (y + menuHeight > windowHeight) {
                finalY = windowHeight - menuHeight - 10;
            }
            
            contextMenu.css({ left: finalX + 'px', top: finalY + 'px' });
        };
        
        // PC端右键菜单
        $(document).off('contextmenu.emailMenu').on('contextmenu.emailMenu', '.email-item', function(e) {
            e.preventDefault();
            const emailItem = $(this);
            showMenu(e.pageX, e.pageY, emailItem);
            return false;
        });
        
        // 移动端长按菜单
        let touchStartX = 0;
        let touchStartY = 0;
        
        $(document).off('touchstart.emailLongPress').on('touchstart.emailLongPress', '.email-item', function(e) {
            const emailItem = $(this);
            longPressTarget = emailItem;
            
            const touch = e.originalEvent.touches[0];
            touchStartX = touch.pageX;
            touchStartY = touch.pageY;
            
            longPressTimer = setTimeout(() => {
                if (navigator.vibrate) {
                    navigator.vibrate(50);
                }
                showMenu(touchStartX, touchStartY, emailItem);
                longPressTimer = null;
            }, 500);
        });
        
        $(document).off('touchmove.emailLongPress').on('touchmove.emailLongPress', '.email-item', function(e) {
            if (longPressTimer) {
                const touch = e.originalEvent.touches[0];
                const moveX = Math.abs(touch.pageX - touchStartX);
                const moveY = Math.abs(touch.pageY - touchStartY);
                
                if (moveX > 10 || moveY > 10) {
                    clearTimeout(longPressTimer);
                    longPressTimer = null;
                }
            }
        });
        
        $(document).off('touchend.emailLongPress').on('touchend.emailLongPress', '.email-item', function(e) {
            if (longPressTimer) {
                clearTimeout(longPressTimer);
                longPressTimer = null;
            }
        });
        
        // 菜单项点击事件
        contextMenu.off('click').on('click', '.email-context-menu-item', function(e) {
            e.stopPropagation();
            const action = $(this).data('action');
            const emailId = parseInt($(this).data('email-id'));
            const accountId = parseInt($(this).data('account-id'));
            
            hideMenu();
            
            switch(action) {
                case 'mark-read':
                    EmailOperationsManager.markAsRead(accountId, emailId);
                    break;
                case 'mark-unread':
                    EmailOperationsManager.markAsUnread(accountId, emailId);
                    break;
                case 'move':
                    EmailOperationsManager.moveEmail(accountId, emailId, EmailModule.cache.currentFolder);
                    break;
                case 'delete':
                    EmailOperationsManager.deleteEmail(accountId, emailId);
                    break;
                case 'permanent-delete':
                    EmailOperationsManager.permanentDeleteEmail(accountId, emailId);
                    break;
            }
        });
        
        // 点击其他地方隐藏菜单
        $(document).off('click.emailContextMenu').on('click.emailContextMenu', function(e) {
            if (!$(e.target).closest('#email-context-menu').length) {
                hideMenu();
            }
        });
        
        // 滚动时隐藏菜单
        $('#email-list-wrapper').off('scroll.emailContextMenu').on('scroll.emailContextMenu', function() {
            hideMenu();
        });
    }
};